import storage from '@/utils/storage'
import router, { removeDynamicRoutes } from '@/router'

import { ElMessage as Message } from 'element-plus'
import { getInfo } from '@/api/loginUser'
import { fetchDeptTree } from '@/api/loginUser/common'
import { logout } from '@/api/login'

const state = () => ({
  token: storage.get('token'),
  info: storage.get('info') || {},
  depts: storage.get('depts') || [],
})

const mutations = {
  SET_TOKEN(state, token) {
    storage.set('token', token)
    state.token = token
  },
  CLEAR_TOKEN(state) {
    storage.remove('token')
    state.token = null
  },
  SET_INFO(state, info) {
    storage.set('info', info)
    state.info = info
  },
  CLEAR_INFO(state) {
    storage.remove('info')
    state.info = {}
  },
  SET_DEPTS(state, depts) {
    storage.set('depts', depts)
    state.depts = depts
  },
  CLEAR_DEPTS(state) {
    storage.remove('depts')
    state.depts = []
  },
}

const actions = {
  gotoLogin({ commit, dispatch }) {
    let hash = window.location.hash
    if (hash == '#/login') {
      return
    }

    if (hash && hash != '#/') {
      storage.set('redirectUrl', window.location.href)
    } else {
      storage.remove('redirectUrl')
    }

    removeDynamicRoutes()

    commit('CLEAR_INFO')
    commit('CLEAR_DEPTS')
    commit('CLEAR_TOKEN')
    commit('menu/CLEAR_MENUS', null, { root: true })
    commit('menu/CLEAR_INDEX_MENU', null, { root: true })
    commit('menu/CLEAR_PERMISSIONS', null, { root: true })

    dispatch('stomp/disConnect', null, { root: true })

    router.push('/login')
  },
  loginSuccess({ dispatch, commit }, token) {
    removeDynamicRoutes()

    commit('CLEAR_INFO')
    commit('CLEAR_DEPTS')
    commit('menu/CLEAR_MENUS', null, { root: true })
    commit('menu/CLEAR_INDEX_MENU', null, { root: true })
    commit('menu/CLEAR_PERMISSIONS', null, { root: true })

    commit('SET_TOKEN', token)

    dispatch('menu/getMenus', null, { root: true })
  },
  logout({ dispatch }) {
    logout().then(() => {
      Message({
        message: '安全退出',
        dangerouslyUseHTMLString: true,
        type: 'success',
      })

      dispatch('gotoLogin')
      storage.remove('redirectUrl')
    })
  },
  async getInfo({ commit, dispatch }) {
    const res = await getInfo()
    let info = res.data.data

    commit('SET_INFO', info)
    dispatch('getUserDept')
  },
  getUserDept({ state, commit }) {
    let userDeptId = state.info.userDeptId
    fetchDeptTree(userDeptId).then((res) => {
      let depts = res.data.data
      if (userDeptId == 0) {
        depts.push({
          id: 0,
          deptName: '根部门',
        })
      }
      commit('SET_DEPTS', depts)
    })
  },
}

export default {
  namespaced: true,
  state: state,
  actions: actions,
  mutations: mutations,
}
